import Vue from 'vue'
import VCharts from 'v-charts'
import 'normalize.css/normalize.css' // A modern alternative to CSS resets
import {getUser} from '@/utils/auth' // get token from cookie
const timeUtils = require("@/js/dateUtils.js");

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import locale from 'element-ui/lib/locale/lang/zh-CN' // lang i18n

import '@/styles/index.scss' // global css

import App from './App'
import store from './store'
import router from './router'

import '@/icons' // icon
import '@/permission' // permission control

import common from './js/common' // 引入
Vue.use(common) // 添加
Vue.use(VCharts)

import {getQiNiuToken, deleteFile} from './api/file/qiniu'
import md5 from 'js-md5'

var FileUtils = require('./js/FileUtils.js')
var qiniu = require('qiniu-js')


/**
 * If you don't want to use mock-server
 * you want to use MockJs for mock api
 * you can execute: mockXHR()
 *
 * Currently MockJs will be used in the production environment,
 * please remove it before going online ! ! !
 */
// if (process.env.NODE_ENV === 'production') {
//   const {mockXHR} = require('../mock')
//   mockXHR()
// }

// set ElementUI lang to EN
Vue.use(ElementUI, {locale})
// 如果想要中文版 element-ui，按如下方式声明
// Vue.use(ElementUI)
import scroll from 'vue-seamless-scroll'
Vue.use(scroll)


Vue.config.productionTip = false

Vue.filter("formatBeforeTime33", function (timestamp) { //传入时间戳
  return timeUtils.formatBeforeTime3(timestamp)
})
Vue.filter("formatBeforeTime3", function (dateStr) { //传入时间格式 yyyy-MM-dd HH:mm:ss
  return timeUtils.formatBeforeTime3(timeUtils.getDateByTimestamp(dateStr))
})


new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})
/**
 * 存储对象
 * @param object
 * @returns {boolean}
 */
Vue.prototype.setItem = function (key, object) {
  localStorage.setItem(key, JSON.stringify(object))
}
/**
 * 清除存储对象
 * @param object
 * @returns {boolean}
 */
Vue.prototype.clearItem = function (key) {
  localStorage.setItem(key, '')
}
/**
 * 取出对象
 * @param object
 * @returns {boolean}
 */
Vue.prototype.getItem = function (key, object) {
  const value = localStorage.getItem(key)
  if (!this.isEmpty(value)) {
    return JSON.parse(value)
  } else {
    return null
  }
}

Vue.prototype.getUser = function (needAccessList) {
  return getUser();
}
/**
 * 循环对比是否有权限
 * @param object
 * @returns {boolean}
 */
Vue.prototype.isHadPermission = function (needAccessList) {
  if (needAccessList == null || needAccessList == undefined) {
    needAccessList = []
  }
  needAccessList.push('superManager')//默认附加超管权限

  const user = getUser()
  const userAccessList = user.accessList

  if (needAccessList == null || needAccessList == undefined) {
    return false
  }
  for (let i = 0; i < userAccessList.length; i++) {
    for (let j = 0; j < needAccessList.length; j++) {
      if (userAccessList[i] == needAccessList[j]) {
        // console.log('有权限 ' + JSON.stringify(needAccessList))
        return true
      }
    }
  }
  // console.log('无权限 ' + JSON.stringify(needAccessList))
  return false
}
/**
 * 无权限提示
 * @param object
 * @returns {boolean}
 */
Vue.prototype.noPermissionHint = function (str) {
  this.$notify.error({
    title: '权限提示',
    message: this.isEmpty(str) ? '您暂无权限' : str,
    duration: 1000
  })
}
/**
 * 对象是否为空
 * @param object
 * @returns {boolean}
 */
Vue.prototype.isEmpty = function (object) {
  if (object == null || object === '' || object == undefined) {
    return true
  }
  return false
}


/**得到文件后缀*/
// Vue.prototype.getSuffix = function(fileNameOrPath) {
// 	var last_len = fileNameOrPath.lastIndexOf(".");
// 	var len = fileNameOrPath.length;
// 	var pathf = fileNameOrPath.substring(last_len + 1, len);
// 	return pathf;
// }

Vue.prototype.getSingleName = function (srcName) {
  var single = md5(Number(Math.random().toString().substr(3, 5) + Date.now()).toString())
  var name = single + '.' + FileUtils.getSuffix(srcName)
  return name
}

var subscription = null

Vue.prototype.cancelUpload = function () {
  subscription.unsubscribe() // 上传取消
}

Vue.prototype.uploadIndex = 0 //上传文件的索引
Vue.prototype.uploadList = [] //上传文件的索引

/**上传成功后返回上传成功图片的key值（唯一键）*/
Vue.prototype.uploadMultipleFile = function (fileList, token, onUploadSuccess, onUploadProgress, onUploadError) {
  const _this = this

  if (_this.isEmpty(token)) {
    //当token为空的时候重置队列
    _this.uploadIndex = 0
    _this.uploadList = []
    _this.getQiniuToken(function (token) {
      _this.uploadFile(fileList[_this.uploadIndex], token, function (key, url) { //成功
        _this.uploadList.push({
          key: key,
          url: url
        })
        _this.uploadIndex++ //上传 成功后自加
        if (fileList.length == _this.uploadIndex) { //已经是最后一个上传的文件了
          if (onUploadSuccess) {
            onUploadSuccess(_this.uploadList)
          }
        } else {
          // if (onUploadSuccess) {
          //   onUploadSuccess(_this.uploadIndex, fileList.length)
          // }
          _this.uploadMultipleFile(fileList, token, onUploadSuccess, onUploadProgress, onUploadError)
        }
      }, function (percent) {
        if (onUploadProgress) {
          onUploadProgress(_this.uploadIndex + 1, fileList.length, percent)
        }
      }, function (err) {
        if (onUploadError) {
          onUploadError(err)
        }
      })
    }, function (error) {

    })
  } else {
    _this.uploadFile(fileList[_this.uploadIndex], token, function (key, url) { //成功
      _this.uploadList.push({
        key: key,
        url: url
      })
      _this.uploadIndex++ //上传 成功后自加
      if (fileList.length == _this.uploadIndex) { //已经是最后一个上传的文件了
        if (onUploadSuccess) {
          onUploadSuccess(_this.uploadList)
        }
      } else {
        if (onUploadSuccess) {
          onUploadSuccess(_this.uploadIndex, fileList.length)
        }
        _this.uploadMultipleFile(fileList, token, onUploadSuccess, onUploadProgress, onUploadError)
      }
    }, function (precent) {
      if (onUploadProgress) {
        onUploadProgress(_this.uploadIndex + 1, fileList.length, precent)
      }
    }, function (err) {
      if (onUploadError) {
        onUploadError(err)
      }
    })
  }

}

Vue.prototype.deleteFile = function (imgName, onSuccess, onError) {
  const _this = this

  const data = new FormData()
  data.append('imgQiNiuName', imgName)
  deleteFile(data).then(response => {
    if (onSuccess) {
      onSuccess()
    }
  }).catch((e) => {
    console.log(e)
    if (onError) {
      onError()
    }
    _this.$message({
      message: '删除失败',
      type: 'error',
      duration: 3000
    })
  })
}

Vue.prototype.getQiniuToken = function (onSuccess, onError) {
  const _this = this

  const data = new FormData()

  getQiNiuToken(data).then(response => {
    var token = response.data
    if (onSuccess) {
      onSuccess(token)
    }

  }).catch((e) => {
    console.log(e)
    _this.$message({
      message: '获取token失败,上传失败',
      type: 'error',
      duration: 3000
    })
  })

}

/**上传成功后返回上传成功图片的key值（唯一键）*/
Vue.prototype.uploadFile = function (file, token, onUploadSuccess, onUploadProgress, onUploadError) {
  const _this = this
  var newName = _this.getSingleName(file.name)

  console.log('开始上传 ' + newName)
  const config = {
    useCdnDomain: true,
    // region: qiniu.region.z2
    region: null,//region: 选择上传域名区域；当为 null 或 undefined 时，自动分析上传域名区域
    retryCount: 3//重试次数
  }
  const putExtra = {
    fname: '',
    params: {},
    mimeType: null
  }

  var observer = {
    next(res) {
      const total = res.total
      console.log('进度：' + total.percent + '% ')
      // toast.message = "上传进度: " + Number(total.percent).toFixed(0) + "%";
      if (onUploadProgress) {
        onUploadProgress(total.percent)
      }
    },
    error(err) {
      console.log(err)
      if (onUploadError) {
        onUploadError('上传失败')
      }
    },
    complete(res) {
      const domain = process.env.VUE_APP_QINIU_BASE_URL
      const url = domain + '/' + res.key;
      console.log('上传结束地址:' + url)
      if (onUploadSuccess) {
        onUploadSuccess(res.key, url)
      }
    }
  }

  console.log(qiniu)
  var observable = qiniu.upload(file, newName, token, putExtra, config)
  const subscription = observable.subscribe(observer) // 上传开始
  // var subscription = observable.subscribe(next, error, complete) // 这样传参形式也可以

}

/**上传成功后返回上传成功图片的key值（唯一键）*/
Vue.prototype.uploadSingleFile = function (file, onUploadSuccess, onUploadProgress, onUploadError) {
  const _this = this

  _this.getQiniuToken(function (token) {
    _this.uploadFile(file, token, onUploadSuccess, onUploadProgress, onUploadError)
  }, function (error) {

  })
}

//替换所有要替换的文字
String.prototype.replaceAll = function (str1, str2) {
  var str = this;
  var result = str.replace(eval("/" + str1 + "/gi"), str2);
  return result;
}


// 注册一个全局自定义指令 `v-has-permission`
// el: 指令所绑定的元素，可以用来直接操作 DOM 。
// binding: 一个对象，包含以下属性：
//   name: 指令名，不包括 v- 前缀。
//   value: 指令的绑定值， 例如： v-my-directive="1 + 1", value 的值是 2。
//   oldValue: 指令绑定的前一个值，仅在 update 和 componentUpdated 钩子中可用。无论值是否改变都可用。
//   expression: 绑定值的字符串形式。 例如 v-my-directive="1 + 1" ， expression 的值是 "1 + 1"。
//   arg: 传给指令的参数。例如 v-my-directive:foo， arg 的值是 "foo"。
//   modifiers: 一个包含修饰符的对象。 例如： v-my-directive.foo.bar, 修饰符对象 modifiers 的值是{ foo: true, bar: true }。
// vnode: Vue 编译生成的虚拟节点，查阅 VNode API 了解更多详情。
// oldVnode: 上一个虚拟节点，仅在 update 和 componentUpdated 钩子中可用。
Vue.directive('hasPermission', {
  // 当被绑定的元素插入到 DOM 中时……
  //被绑定元素插入父节点时调用（父节点存在即可调用，不必存在于 document 中）
  inserted: function (el,binding) {
    var flag = false;
    var data = binding.value;
    var needAccessList;

    if (data == null || data == undefined) {
      needAccessList = []
    } else if (data instanceof Array) {
      needAccessList = data;
    } else {
      needAccessList = [data]
    }

    needAccessList.push('superManager')//默认附加超管权限
    const user = getUser()
    const userAccessList = user.accessList
    for (let j = 0; j < needAccessList.length; j++) {
      if (userAccessList.includes(needAccessList[j])) {
        flag = true
      }
    }
    if (!flag) {
      // 聚焦元素
      el.parentNode.removeChild(el)
    }
  },
  //bind: 只调用一次，指令第一次绑定到元素时调用，用这个钩子函数可以定义一个在绑定时执行一次的初始化动作
  bind(el,binding){},
  //update: 被绑定元素所在的模板更新时调用，而不论绑定值是否变化。通过比较更新前后的绑定值，可以忽略不必要的模板更新
  update(){},
  //componentUpdated: 被绑定元素所在模板完成一次更新周期时调用
  componentUpdated(){},
  //unbind: 只调用一次， 指令与元素解绑时调用
  unbind(){}

})

// if (!this.isHadPermission(["superManager", "查看统计(全项目)"])) {
//   let companyId = this.user.companyId;
//   if (!this.isEmpty(companyId)) {
//     this.userCompany = await this.getCompany(companyId);
//   } else {
//     this.$message('用户未配置公司')
//     return;
//   }
//
//   if (this.userCompany == null) {
//     this.$message('用户未配置公司')
//     return;
//   }
//   //过滤省份筛选数据
//   this.userCityList = [];
//   this.userProvinceList = []
//   for (let i = 0; i < this.userCompany.children.length; i++) {
//     let city = this.userCompany.children[i].city
//     let province = this.userCompany.children[i].province
//
//     if (!this.userProvinceList.includes(province)) {
//       this.userProvinceList.push(province)
//     }
//     if (!this.userCityList.includes(city)) {
//       this.userCityList.push(city)
//     }
//   }
//
//   if (this.userCityList.length == 0) {
//     this.$message({
//       message: '用户未配置公司，或该公司下未配置城市',
//       type: 'error'
//     })
//     return;
//   }
//   this.params['city_in'] = this.userCityList;
//
//   //过滤区域公司数据
//   for (let i = 0; i < this.companyList.length; i++) {
//     if (this.companyList[i].id != this.user.companyId) {
//       this.companyList.splice(i--, 1)
//     }
//   }
//
//
// }
